package com.vogue.supplymall.admin.business.domain.biz.impl;

import com.vogue.supplymall.admin.business.domain.biz.OpenOrganBiz;
import com.vogue.supplymall.admin.business.domain.biz.TaskProcessorBiz;
import com.vogue.supplymall.admin.business.domain.model.AdminAccountBalance;
import com.vogue.supplymall.admin.business.domain.model.AdminAccountBill;
import com.vogue.supplymall.admin.business.domain.model.AdminCheckLicence;
import com.vogue.supplymall.admin.business.domain.model.AdminConsumeProduct;
import com.vogue.supplymall.admin.business.domain.model.AdminOrgan;
import com.vogue.supplymall.admin.business.domain.model.AdminPlatform;
import com.vogue.supplymall.admin.business.domain.service.AdminAccountBalanceService;
import com.vogue.supplymall.admin.business.domain.service.AdminAccountBillService;
import com.vogue.supplymall.admin.business.domain.service.AdminCheckLicenceService;
import com.vogue.supplymall.admin.business.domain.service.AdminConsumeProductService;
import com.vogue.supplymall.admin.business.domain.service.AdminOrganService;
import com.vogue.supplymall.admin.business.domain.service.AdminPlatformService;
import com.vogue.supplymall.match.domain.model.MatchOrgan;
import com.vogue.supplymall.match.domain.service.MatchOrganService;
import com.vogue.supplymall.order.domain.model.Order;
import com.vogue.supplymall.order.domain.service.OrderService;
import com.vogue.supplymall.shop.domain.model.Shop;
import com.vogue.supplymall.shop.domain.service.ShopService;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * The type Task processor biz.
 *
 * @aouthor: zhangliang
 * @date: Create in 2018-05-24
 */
@Service("taskProcessorBiz")
public class TaskProcessorBizImpl implements TaskProcessorBiz {
    /**
     * The constant log.
     */
    public static final Logger LOGGER_TASKPROCESSORBIZIMPL = LoggerFactory.getLogger(TaskProcessorBizImpl.class);

    @Resource
    private AdminCheckLicenceService adminCheckLicenceService;
    @Resource
    private MatchOrganService matchOrganService;
    @Resource
    private ShopService shopService;
    @Resource
    private AdminConsumeProductService adminConsumeProductService;
    @Resource
    private AdminOrganService adminOrganService;
    @Resource
    private OpenOrganBiz openOrganBiz;
    @Resource
    private AdminPlatformService adminPlatformService;
    @Resource
    private AdminAccountBalanceService adminAccountBalanceService;
    @Resource
    private AdminAccountBillService adminAccountBillService;
    @Resource
    private OrderService orderService;
    // 获取现金+信用的余额总额
    private Function<List<AdminAccountBalance>, BigDecimal> calcBalance = (list) -> list
            .stream()
            .map((b) -> b.getBalance())
            .reduce(BigDecimal.ZERO, BigDecimal::add);

    @Override
    @Transactional
    public void checkShopLicence2() {
        LOGGER_TASKPROCESSORBIZIMPL.info("审核店铺证照的任务 start");
        // 查询可用的申请操作
        String sql = " disabledflag = 0 and type = 0";
        List<AdminCheckLicence> result = adminCheckLicenceService.selectByWhr(sql);
        Date openDate = null;
        Boolean jobDisadle = true;
        for (AdminCheckLicence checkInfo : result) {
            jobDisadle = true;
            // 检索用通用参数
            Map<String, Object> para = new HashMap<>();
            para.put("syscodeid", checkInfo.getSyscodeid());
            String platformSql = " syscodeid = #{syscodeid} and disabledflag = false; ";
            List<AdminPlatform> platformList = adminPlatformService.selectByWhr0(platformSql, para);
            List<Integer> platform = platformList.stream().map((plat) -> plat.getPlatform()).collect(Collectors.toList());

            if (checkInfo.getOnoff() == 0) {
                // 查询集团下的店铺(多平台店铺开通)
                String sqls = " syscodeid = #{syscodeid} and matchid = #{matchid} order by matchid,opendate desc";
                para.put("matchid", checkInfo.getMatchid());
                List<Shop> shops = shopService.selectByWhr0(sqls, para);
                int cnt = 0;
                for (Shop shop : shops) {
                    // 开通已开通平台的店铺
                    if (platform.contains(shop.getTendid())) {
                        if (null != shop.getOpendate()) {
                            openDate = shop.getOpendate();
                        }
                        // 如果店铺未开通，更新店铺为开通
                        if (shop.getDisabledflag()) {
                            if (null != shop.getOpendate()) {
                                if (new Date().compareTo(openDate) >= 0) {
                                    shop.setDisabledflag(false);
                                    shop.setModifyDate(new Date());
                                    shopService.update(shop);
                                    cnt++;
                                    LOGGER_TASKPROCESSORBIZIMPL.info("开通店铺-shop：" + shop.getName() + "matchid:" + shop.getMatchid());
                                } else {
                                    // 开通日期没到任务不禁用
                                    jobDisadle = false;
                                }
                            } else {
                                LOGGER_TASKPROCESSORBIZIMPL.error("data error , open date is null ");
                                // 开通日期为空不属于正常情况，任务不禁用
                                jobDisadle = false;
                            }
                        }
                    }
                }
                // 开通集团
                if (cnt > 0) {
                    openOrgan(checkInfo, openDate, platform);
                }
            } else {
                String sqlm = " syscodeid = #{syscodeid} and matchid = #{matchid}";
                para.put("matchid", checkInfo.getMatchid());
                List<Shop> shops = shopService.selectByWhr0(sqlm, para);
                for (Shop shop : shops) {
                    shop.setDisabledflag(true);
                    shop.setModifyDate(new Date());
                    shopService.update(shop);
                    LOGGER_TASKPROCESSORBIZIMPL.info("关闭店铺-shop：" + shop.getName() + "matchid:" + shop.getMatchid());
                }
                // 关闭集团
                closeOrgan(checkInfo);
            }

            // 更新admin_checklicence
            checkInfo.setDisabledflag(jobDisadle);
            checkInfo.setModifyDate(new Date());
            adminCheckLicenceService.update(checkInfo);
            LOGGER_TASKPROCESSORBIZIMPL.info("更新 admin_checklicence：disable = " + checkInfo.getDisabledflag());
        }
        LOGGER_TASKPROCESSORBIZIMPL.info("审核店铺证照的任务 end");
    }

    /**
     * 设置当前计费产品生效日期、结束日期
     *
     * @param syscodeid syscodeid
     * @param openDate  openDate
     */
    private void updateAdminConsume(Long syscodeid, Date openDate) {
        // 设置当前计费产品生效日期
        String sql = " syscodeid = #{syscodeid} and validtype = 0";
        Map<String, Object> para = new HashMap<>();
        para.put("syscodeid", syscodeid);
        List<AdminConsumeProduct> result = adminConsumeProductService.selectByWhr0(sql, para);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(openDate);
        calendar.add(Calendar.YEAR, 1);
        Date endDate = calendar.getTime();
        if (result.size() > 0) {
            AdminConsumeProduct adminConsumeProduct = result.get(0);
            adminConsumeProduct.setStartdate(openDate);
            adminConsumeProduct.setEnddate(endDate);
            adminConsumeProductService.update(adminConsumeProduct);
            LOGGER_TASKPROCESSORBIZIMPL.info("设置当前计费产品生效日期、结束日期。当前集团 syscodeid： " + syscodeid + "的计费时间已生效！");
        }
    }

    /**
     * 更新开通时间
     *
     * @param syscodeid syscodeid
     * @param openDate  openDate
     */
    private void updateAdminOrgan(Long syscodeid, Date openDate) {
        // 更新开通时间
        String sql = " syscodeid = #{syscodeid} and opendate is null";
        Map<String, Object> para = new HashMap<>();
        para.put("syscodeid", syscodeid);
        List<AdminOrgan> result = adminOrganService.selectByWhr0(sql, para);
        if (result.size() > 0) {
            AdminOrgan adminOrgan = result.get(0);
            adminOrgan.setOpendate(openDate);
            adminOrgan.setModifyDate(new Date());
            adminOrganService.update(adminOrgan);
            LOGGER_TASKPROCESSORBIZIMPL.info("更新开通时间。当前集团 syscodeid： " + syscodeid + "的开通时间：" + openDate.toString());

            // 设置当前计费产品生效日期
            updateAdminConsume(syscodeid, openDate);
        }
    }

    /**
     * 开通集团
     * 集团首次开通时，更新计费信息的生效时间、更新开通时间
     *
     * @param checkInfo checkInfo
     * @param openDate  the open date
     * @param platform  the platform
     */
    private void openOrgan(AdminCheckLicence checkInfo, Date openDate, List<Integer> platform) {
        String sql = " syscodeid = #{syscodeid}";
        Map<String, Object> para = new HashMap<>();
        para.put("syscodeid", checkInfo.getSyscodeid());
        List<MatchOrgan> result = matchOrganService.selectByWhr0(sql, para);
        for (MatchOrgan matchOrgan : result) {
            // 开通已开通平台的集团
            if (platform.contains(matchOrgan.getTendid())) {
                // 开通集团（开通店铺之前，集团肯定开通过）
                if (matchOrgan.getType() == 1) {
                    if (matchOrgan.isDisabledflag()) {
                        matchOrgan.setDisabledflag(false);
                        matchOrganService.update(matchOrgan);
                        LOGGER_TASKPROCESSORBIZIMPL.info("开通集团 matchOrgan：" + matchOrgan.getOrgname() + "matchid:" + matchOrgan.getMatchid());
                    }

                    // 更新开通时间
                    updateAdminOrgan(checkInfo.getSyscodeid(), openDate);
                }
                // 如果是当前审核的店铺就开通店铺
                if (checkInfo.getMatchid().equals(matchOrgan.getMatchid())) {
                    matchOrgan.setDisabledflag(false);
                    matchOrganService.update(matchOrgan);
                    LOGGER_TASKPROCESSORBIZIMPL.info("开通店铺 matchOrgan：" + matchOrgan.getOrgname() + "matchid:" + matchOrgan.getMatchid());
                }
            }
        }
    }

    /**
     * 关闭店铺
     * 停用按钮触发时集团关闭
     *
     * @param checkInfo checkInfo
     */
    private void closeOrgan(AdminCheckLicence checkInfo) {
        String sql = " syscodeid = #{syscodeid}";
        Map<String, Object> para = new HashMap<>();
        para.put("syscodeid", checkInfo.getSyscodeid());
        List<MatchOrgan> result = matchOrganService.selectByWhr0(sql, para);
        MatchOrgan organ = new MatchOrgan();
        // 关闭店铺的计数器
        for (MatchOrgan matchOrgan : result) {
            // 关闭集团
            if (matchOrgan.getType() == 1) {
                organ = matchOrgan;
            }
            // 先关闭店铺
            if (checkInfo.getMatchid().equals(matchOrgan.getMatchid())) {
                matchOrgan.setDisabledflag(true);
                matchOrganService.update(matchOrgan);
                LOGGER_TASKPROCESSORBIZIMPL.info("关闭店铺 matchOrgan：" + matchOrgan.getOrgname() + "matchid:" + matchOrgan.getMatchid());
            }
        }

        // 2018/6/7 集团在不是停用的情况下，不设置关闭
        if (checkInfo.getType() == 1 && checkInfo.getOnoff() == 1) {
            organ.setDisabledflag(true);
            matchOrganService.update(organ);
            LOGGER_TASKPROCESSORBIZIMPL.info("开通集团 matchOrgan：" + organ.getOrgname() + "matchid:" + organ.getMatchid());
        }
    }

    @Override
    @Transactional
    public Boolean doOnoffOrgan() {
        LOGGER_TASKPROCESSORBIZIMPL.info("关闭停用集团 start");
        // 查询可用的申请操作
        String sql = " disabledflag = 0 and type = 1";
        List<AdminCheckLicence> result = adminCheckLicenceService.selectByWhr(sql);
        for (AdminCheckLicence checkInfo : result) {
            // 开通店铺集团
            if (checkInfo.getOnoff() == 0) {
                Map<String, Object> para = new HashMap<>();
                para.put("syscodeid", checkInfo.getSyscodeid());
                String platformSql = " syscodeid = #{syscodeid} and disabledflag = false; ";
                List<AdminPlatform> platformList = adminPlatformService.selectByWhr0(platformSql, para);
                if (platformList.size() > 0) {
                    // 在多平台开启集团
                    for (AdminPlatform platform : platformList) {
                        para.put("tendid", platform.getPlatform());
                        // 强制开启集团下的店铺(多平台店铺开通)
                        String onShopSql = " update licence_apply la,match_organ mo set mo.disabledflag = 0 "
                                + " where mo.syscodeid = la.syscodeid  and mo.matchid = la.matchid "
                                + " and mo.syscodeid = #{syscodeid} and mo.disabledflag = 1 "
                                + "and la.applytype = 1 AND la.applystatue = 1 AND mo.tendid = #{tendid}";
                        shopService.update0(onShopSql, para);
                        // 开通集团
                        String openOrganSql = "update match_organ set disabledflag = 0 where syscodeid = #{syscodeid} "
                                + "and type = 1 AND tendid = #{tendid}";
                        shopService.update0(openOrganSql, para);
                        // 开启match表的集团和店铺
                        String onOrganSql = "update licence_apply la,shop mo set mo.disabledflag = 0 "
                                + " where mo.syscodeid = la.syscodeid  and mo.matchid = la.matchid "
                                + " and mo.syscodeid = #{syscodeid} and mo.disabledflag = 1 "
                                + "and la.applytype = 1 AND la.applystatue = 1 AND mo.tendid = #{tendid}";
                        matchOrganService.update0(onOrganSql, para);
                    }
                }

                // 开启后证照过期的店铺处理
                openOrganBiz.checkShopLicence();
            } else {
                // 强制关闭集团下的店铺(多平台店铺开通)
                String onShopSql = "update shop set disabledflag = 1 where syscodeid =  #{syscodeid}";
                Map<String, Object> para = new HashMap<>();
                para.put("syscodeid", checkInfo.getSyscodeid());
                shopService.update0(onShopSql, para);
                // 关闭match表的集团和店铺
                String onOrganSql = "update match_organ set disabledflag = 1 where syscodeid =  #{syscodeid}";
                matchOrganService.update0(onOrganSql, para);
            }
            checkInfo.setDisabledflag(true);
            adminCheckLicenceService.update(checkInfo);
        }
        LOGGER_TASKPROCESSORBIZIMPL.info("关闭停用集团 end");
        return true;
    }

    @Override
    public void accountConsume() {
        LOGGER_TASKPROCESSORBIZIMPL.info("集团计费处理 start");
        // 包年服务
        getEndProduct(1);
        // 包月服务
        getEndProduct(2);
        // 按单扣点
        accountConsumeForPoint();
        LOGGER_TASKPROCESSORBIZIMPL.info("集团计费处理 end");
    }

    /**
     * Gets end product.
     *
     * @param consumetype the consumetype
     */
    public void getEndProduct(Integer consumetype) {
        if (consumetype != 1 || consumetype != 2) {
            LOGGER_TASKPROCESSORBIZIMPL.error("包年、包月的费用计算时错误");
            return;
        }
        Map<String, Object> para = new HashMap<>();
        String sqlA = " consumetype = #{consumetype} and enddate <= NOW() and disabledflag = 0 and validtype = 0 ";
        para.put("consumetype", consumetype);
        List<AdminConsumeProduct> result = adminConsumeProductService.selectByWhr0(sqlA, para);
        for (AdminConsumeProduct product : result) {
            // 包年服务
            calcCost(product);
            // 包月服务
            calcCost(product);
        }
    }

    /**
     * 包年或者包月的费用计算
     * 1.取出超时的计费信息
     * 2.查看余额够不够
     * 3.余额足，如果有续费计费信息，按续费信息计算
     * 4.余额足，如果没有续费信息，按照当前计算
     * 5.没有续约，添加新的计费信息，更新当前计费信息为历史
     * 有续约，更新续约为当前和更新当前为历史（又复杂了。。。）
     * 6.修改余额信息，包括修改现金和信用
     * 7.增加一条消费账单信息
     * 8.余额不足，关闭集团和店铺
     *
     * @param product the product
     */
    @Transactional
    public void calcCost(AdminConsumeProduct product) {
        LOGGER_TASKPROCESSORBIZIMPL.info("包年服务 start");
        Map<String, Object> para = new HashMap<>();
        BigDecimal balance;
        String bSql = " consumeid = #{consumeid} order by type ";
        para.put("consumeid", product.getId());
        // 余额查询包括现金和信用
        List<AdminAccountBalance> balances = adminAccountBalanceService.selectByWhr0(bSql, para);
        // 查询续费信息
        String sqlC = " where organid = #{organid} and syscodeid = #{syscodeid} and consumetype = #{consumetype} ";
        para.put("organid", product.getOrganid());
        para.put("syscodeid", product.getSyscodeid());
        para.put("consumetype", product.getConsumetype());
        AdminConsumeProduct renewalProduct = adminConsumeProductService.selectOneByWhr0(sqlC, para);
        // 余额总额
        balance = calcBalance.apply(balances);
        // 费用
        BigDecimal cost = product.getCost();
        // 计算的费用
        BigDecimal costCalc = product.getCost();
        // 如果有续约，下次的计费信息使用
        if (null != renewalProduct) {
            cost = renewalProduct.getCost();
        }
        // 如果余额足够
        if (balance.compareTo(cost) >= 0) {
            // 添加新的计费信息，更新当前计费信息为历史
            updateConsumeProduct(product, renewalProduct);
            // 修改余额信息，包括修改现金和信用
            for (AdminAccountBalance accountBalance : balances) {
                if (accountBalance.getBalance().compareTo(costCalc) >= 0) {
                    accountBalance.setBalance(accountBalance.getBalance().subtract(costCalc));
                    accountBalance.setModifyDate(new Date());
                    adminAccountBalanceService.update(accountBalance);
                    break;
                } else {
                    costCalc = cost.subtract(accountBalance.getBalance());
                    accountBalance.setBalance(BigDecimal.ZERO);
                    accountBalance.setModifyDate(new Date());
                    adminAccountBalanceService.update(accountBalance);
                }
            }
        } else { // 如果余额不足，停用集团
            // 强制关闭集团下的店铺(多平台店铺开通)
            String onShopSql = "update shop set disabledflag = 1 where syscodeid =  #{syscodeid}";
            Map<String, Object> offPara = new HashMap<>();
            para.put("syscodeid", product.getSyscodeid());
            shopService.update0(onShopSql, offPara);
            // 关闭match表的集团和店铺
            String onOrganSql = "update match_organ set disabledflag = 1 where syscodeid =  #{syscodeid}";
            matchOrganService.update0(onOrganSql, offPara);
        }

        // 增加计费账单信息
        AdminAccountBill adminAccountBill = new AdminAccountBill();
        adminAccountBill.setAmount(cost);
        adminAccountBill.setOrganid(product.getOrganid());
        adminAccountBill.setConsumeid(product.getId());
        adminAccountBill.setStartdate(product.getStartdate());
        adminAccountBill.setEnddate(product.getEnddate());
        adminAccountBill.setSyscodeid(product.getSyscodeid());
        adminAccountBill.setUpdateuser("system");
        adminAccountBill.setUpdateuserid(999L);
        adminAccountBillService.save(adminAccountBill);
        LOGGER_TASKPROCESSORBIZIMPL.info("包年服务 end");
    }

    @Override
    public void accountConsumeForPoint() {
        LOGGER_TASKPROCESSORBIZIMPL.info("集团计费处理--按单扣点 start");
        String sql = " consumetype = 3 and enddate <= NOW() and disabledflag = 0 and validtype = 0 ";
        List<AdminConsumeProduct> result = adminConsumeProductService.selectByWhr(sql);
        for (AdminConsumeProduct product : result) {
            calcSingleCost(product);
        }
        // 按单扣点
        LOGGER_TASKPROCESSORBIZIMPL.info("集团计费处理--按单扣点 end");
    }

    /**
     * 1.取出超时的计费信息，取出前一天的订单信息，计算费用
     * 2.查看余额够不够
     * 3.余额足，如果有续费计费信息，按续费信息计算
     * 4.余额足，如果没有续费信息，按照当前计算
     * 5.没有续约，添加新的计费信息，更新当前计费信息为历史
     * 有续约，更新续约为当前和更新当前为历史（又复杂了。。。）
     * 6.修改余额信息，包括修改现金和信用
     * 7.增加一条消费账单信息
     * 8.余额不足，关闭集团和店铺
     *
     * @param product the product
     */
    @Transactional
    public void calcSingleCost(AdminConsumeProduct product) {
        BigDecimal balance;
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = adjustDate(new Date(), Calendar.DAY_OF_MONTH, -1);
        // 取出前一天应该结算费用的订单
        String sql = "select o.finalprice,o.id,o.syscodeid from `order` o INNER JOIN order_status os on (o.id = os.orderid) "
                + " where o.syscodeid = #{syscodeid} and os.iscancel = 0 and os.orderstatus = 4"
                + " and DATE_FORMAT(os.modifydate ,'%Y-%m-%d') = #{date}";
        Map<String, Object> para = new HashMap<>();
        para.put("syscodeid", product.getSyscodeid());
        para.put("modifydate", format.format(date));
        List<Order> orders = orderService.selectByWhr0(sql, para);
        BigDecimal cost;
        for (Order order : orders) {
            cost = BigDecimal.ZERO;
            if (null != product.getSingleratio()) {
                cost = order.getFinalprice().multiply(product.getSingleratio());
            }

            if (null != product.getMinimum()) {
                if (product.getMinimum().compareTo(cost) > 0) {
                    cost = product.getMinimum();
                }
            }

            if (null != product.getUpperlimit()) {
                if (cost.compareTo(product.getUpperlimit()) > 0) {
                    cost = product.getUpperlimit();
                }
            }
            product.setCost(cost);
            // 计算费用
            calcCost(product);
        }
    }

    /**
     * 更新计费产品信息
     *
     * @param product        the product
     * @param renewalProduct the renewal product
     */
    private void updateConsumeProduct(AdminConsumeProduct product, AdminConsumeProduct renewalProduct) {
        AdminConsumeProduct addProduct = new AdminConsumeProduct();
        try {
            // 如果存在续约，将续约作为下次计费信息
            if (null != renewalProduct) {
                BeanUtils.copyProperties(addProduct, product);
            } else { // 使用当前计费作为下次计费信息
                BeanUtils.copyProperties(addProduct, product);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            LOGGER_TASKPROCESSORBIZIMPL.error("BeanUtils.copyProperties 失败，调用者没有get set方法 ");
        } catch (InvocationTargetException e) {
            e.printStackTrace();
            LOGGER_TASKPROCESSORBIZIMPL.error("BeanUtils.copyProperties 失败，属性访问器抛出异常");
        }
        // 按年计费
        if (addProduct.getConsumetype() == 1) {
            // 设置计费开始时间
            addProduct.setStartdate(adjustDate(addProduct.getStartdate(), Calendar.YEAR, 1));
            // 设置计费结束时间
            addProduct.setEnddate(adjustDate(addProduct.getEnddate(), Calendar.YEAR, 1));
        }
        // 按月计费
        if (addProduct.getConsumetype() == 2) {
            // 设置计费开始时间
            addProduct.setStartdate(adjustDate(addProduct.getStartdate(), Calendar.MONTH, 1));
            // 设置计费结束时间
            addProduct.setEnddate(adjustDate(addProduct.getEnddate(), Calendar.MONTH, 1));
        }
        addProduct.setCreateDate(new Date());
        addProduct.setModifyDate(new Date());
        addProduct.setUpdateuserid(999L);
        addProduct.setUpdateuser("system");
        if (null != renewalProduct) {
            // 更新续约为当前
            addProduct.setValidtype(0);
            adminConsumeProductService.update(addProduct);
        } else {
            // 添加一个新的当前的计费产品信息
            adminConsumeProductService.save(addProduct);
        }
        // 更新当前计费信息为历史
        product.setValidtype(3);
        adminConsumeProductService.update(product);
    }

    /**
     * 返回一个指定年月日的时间
     *
     * @param date   the date
     * @param ymd    the ymd
     * @param adjust the adjust
     * @return date
     */
    private Date adjustDate(Date date, int ymd, int adjust) {
        Calendar calendarY = Calendar.getInstance();
        calendarY.setTime(date);
        calendarY.add(ymd, adjust);
        return calendarY.getTime();
    }
}
